package com.goodlearning.gloriamobile.activity;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.goodlearning.gloriamobile.R;
import com.goodlearning.gloriamobile.adapter.CustomAdapter;
import com.goodlearning.gloriamobile.adapter.CustomAdapter.IListItemController;
import com.goodlearning.gloriamobile.commons.AutoScaleDialog;
import com.goodlearning.gloriamobile.commons.Utils;
import com.goodlearning.gloriamobile.dto.GetPaymentBankViewDto;
import com.goodlearning.gloriamobile.dto.GetPaymentListDto;
import com.goodlearning.gloriamobile.net.JsonRequestThread.INetSuccessCallback;
import com.goodlearning.gloriamobile.net.JsonServiceRequester;
import com.goodlearning.gloriamobile.net.JsonWrapper;
/**
 * 등록금 납부확인 Activity 
 * @author rapty54
 *
 */
public class AdministrationPayTution extends BaseActivity {
	
	ArrayList<GetPaymentListDto> getPaymentListDtos;
	
	CustomAdapter<GetPaymentListDto> customAdapter;
	
	GetPaymentBankViewDto getPaymentBankViewDto;
	
	ArrayList<GetPaymentBankViewDto> bankViewDtos;
	
	ListView listView;
	
	AutoScaleDialog autoScaleDialog;
	
	int doubleClickPreventCount=0;
	
	int []resourceId={R.id.administration_pay_bank_name,R.id.administration_pay_account_name
			,R.id.administration_pay_deposit_name,R.id.administration_close_pay_Bt
			,R.id.administration_sms_pay_Bt,R.id.administration_kakao_pay_Bt
			,R.id.administration_Email_pay_Bt};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.administration_pay_tution_layout);
		init();
	}
	/**
	 * 초기화 선언부
	 */
	public void init(){
		baseTitleLeftBtn.setVisibility(View.VISIBLE);
		baseTitleLeftBtn.setTextColor(getResources().getColor(R.color.administration_sixth_text_change));
		baseTitleLeftBtn.setText(R.string.btn_char1_shift_1);
		baseTitleLeftBtn.setTextSize(20.0f);
		baseTitleTv.setText("등록금");
		baseTitleRightBtn.setVisibility(View.INVISIBLE);
		
		listView=(ListView)findViewById(R.id.administration_pay_tution_ListView);
		
		requestPayList();
	}
	/**
	 * 납부 상태 메인 요청부
	 */
	public void requestPayList(){
		JsonServiceRequester.requestGetPayment(AdministrationPayTution.this, new String(Base64.encodeBase64(getUserId().getBytes()))
		, new INetSuccessCallback() {
			
			@Override
			public void sendCallback(JsonWrapper jsonWrapper) {
				
				JSONArray jsonArray=jsonWrapper.getRootArray();
				
				Utils.log("JsonArray:"+"["+jsonArray.size()+"]");
				
				getPaymentListDtos=new ArrayList<GetPaymentListDto>();
				
				for(int i=0;i<jsonArray.size();i++){
					
					JSONObject jsonObject=(JSONObject)jsonArray.get(i);
					
					GetPaymentListDto getPaymentListDto=new GetPaymentListDto();
					
					getPaymentListDto.setpId(Utils.convertObjToString(jsonObject.get("pId")));
					getPaymentListDto.setRfId(Utils.convertObjToString(jsonObject.get("rfId")));
					getPaymentListDto.setLastDay(Utils.convertObjToString(jsonObject.get("LastDay")));
					getPaymentListDto.setState(Utils.convertObjToString(jsonObject.get("State")));
					getPaymentListDto.setTotalPay(Utils.convertObjToString(jsonObject.get("TotalPay")));
					getPaymentListDto.setM_id(Utils.convertObjToString(jsonObject.get("m_id")));
					getPaymentListDto.setM_name(Utils.convertObjToString(jsonObject.get("m_name")));
					getPaymentListDto.setRegFee(Utils.convertObjToString(jsonObject.get("RegFee")));
					getPaymentListDto.sethYear(Utils.convertObjToString(jsonObject.get("hYear")));
					getPaymentListDto.setHgCd(Utils.convertObjToString(jsonObject.get("hgCd")));
					getPaymentListDto.setHgNm(Utils.convertObjToString(jsonObject.get("hgNm")));
					getPaymentListDto.setHakgi(Utils.convertObjToString(jsonObject.get("hakgi")));
					getPaymentListDto.setHgwNm(Utils.convertObjToString(jsonObject.get("hgwNm")));
					getPaymentListDto.setRefundMoney(Utils.convertObjToString(jsonObject.get("refundMoney")));
					getPaymentListDto.setDeductFee(Utils.convertObjToString(jsonObject.get("DeductFee")));
					getPaymentListDto.settNm(Utils.convertObjToString(jsonObject.get("tNm")));
					
					getPaymentListDtos.add(getPaymentListDto);
					
				}
				
				customAdapter=new CustomAdapter<GetPaymentListDto>(AdministrationPayTution.this, R.layout.administration_pay_tution_row
				,getPaymentListDtos, listItemController);
				listView.setAdapter(customAdapter);
//				listView.setOnItemClickListener(onItemClickListener);
			}
		});
	}
	/**
	 * 
	 */
	protected void onResume() {
		super.onResume();
		Utils.log("==================onResume");
	};
	/**
	 * 통합 Controller
	 * administration_pay_tution_TextView  >> 납부할 금액 RegFee
	 * administration_pay_real_tution_TextView >> 실제로 납부한 금액
	 * administration_pay_tution_total_TextView >> 납부 총액  TotalPay
	 * administration_pay_deduction_total_TextView >> 공제금  DeductFee
	 * administration_pay_refund_total_TextView >> 환불금  refundMoney
	 * administration_pay_end_date_of_payments_TextView >> 최종 납부일  LastDay
	 * administration_pay_show_state_row_TextView >> 납부 상태  State
	 * payOfAccountBt >>> 납부 계좌
	 */
	IListItemController<GetPaymentListDto> listItemController=new IListItemController<GetPaymentListDto>() {

		@Override
		public View controlView(List<GetPaymentListDto> items, final int position,View convertView, ViewGroup parent) {
			
			final GetPaymentListDto getPaymentListDto=(GetPaymentListDto)items.get(position);
			
			/**
			 * 해당 리스트뷰에서 모든 뷰가 이벤트를 발생시키면 안됨으로 상위 레이 아웃에서 막았다.
			 */
			Utils.preventTouchEvent(convertView,R.id.administration_pay_main_layout);
			
			((TextView)convertView.findViewById(R.id.administration_pay_date_of_class_TextView)).setText(getPaymentListDto.gethYear()+"년"+getPaymentListDto.getHakgi()+"학기");
			((TextView)convertView.findViewById(R.id.administration_pay_tution_TextView)).setText(Utils.numberFormatComma(Integer.valueOf(getPaymentListDto.getRegFee()))+"원");
			
			if(Utils.isEmptyCheck(getPaymentListDto.getDeductFee())){
				((TextView)convertView.findViewById(R.id.administration_pay_tution_TextView_state_check)).setVisibility(View.VISIBLE);
				((TextView)convertView.findViewById(R.id.administration_pay_real_tution_TextView)).setText(Utils.numberFormatComma(Integer.valueOf(getPaymentListDto.getTotalPay()))+"원");
			}else{
				((TextView)convertView.findViewById(R.id.administration_pay_tution_TextView_state_check)).setVisibility(View.GONE);
				((TextView)convertView.findViewById(R.id.administration_pay_real_tution_TextView)).setText("");
			}
				                                                                                    
			((TextView)convertView.findViewById(R.id.administration_pay_tution_total_TextView)).setText(Utils.numberFormatComma(Integer.valueOf(getPaymentListDto.getTotalPay()))+"원");
			((TextView)convertView.findViewById(R.id.administration_pay_deduction_total_TextView)).setText(Utils.numberFormatComma(Integer.valueOf(getPaymentListDto.getDeductFee()))+"원");
			((TextView)convertView.findViewById(R.id.administration_pay_refund_total_TextView)).setText(Utils.numberFormatComma(Integer.valueOf(getPaymentListDto.getRefundMoney()))+"원");
			((TextView)convertView.findViewById(R.id.administration_pay_end_date_of_payments_TextView)).setText(getPaymentListDto.getLastDay());
			
			/**
			 * 지불상태 표시
			 */
			
			TextView showState=(TextView)convertView.findViewById(R.id.administration_pay_show_state_row_TextView);
			
			if(Utils.isDataCheck(getPaymentListDto.getState(), "분납")){
				showState.setText(getPaymentListDto.getState());
				showState.setTag(position);
				Utils.log("=================분납");
				showState.setBackgroundColor(Color.rgb(204, 204, 204));
			}else if(Utils.isDataCheck(getPaymentListDto.getState(), "완납")){
				showState.setText(getPaymentListDto.getState());
				showState.setTag(position);
				Utils.log("=================완납");
				showState.setBackgroundColor(Color.rgb(102, 102, 153));
			}else if(Utils.isDataCheck(getPaymentListDto.getState(), "미납")){
				showState.setText(getPaymentListDto.getState());
				showState.setTag(position);
				Utils.log("=================미달");
				showState.setBackgroundColor(Color.rgb(153, 000, 000));
			}
			
			/**
			 * 납부계좌 조회 진입 버튼
			 */
			final TextView payOfAccountBt=(TextView)convertView.findViewById(R.id.payOfAccountBt);
			payOfAccountBt.setText("납부계좌");
			Utils.log("LIST_DTO_ID:"+"["+getPaymentListDto.getpId()+"]");
			payOfAccountBt.setTag(getPaymentListDto.getpId());
			payOfAccountBt.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Utils.log("============================납부계좌 버튼");
					
					JsonServiceRequester.requestGetPaymentBankView(AdministrationPayTution.this, new String(Base64.encodeBase64(getUserId().getBytes()))
					        ,getPaymentListDto.getRfId()
							,getPaymentListDto.gethYear()
							,getPaymentListDto.getHakgi(), new INetSuccessCallback() {
								
								@Override
								public void sendCallback(JsonWrapper jsonWrapper) {
									
									JSONArray jsonArray=jsonWrapper.getRootArray();
									
									bankViewDtos =new ArrayList<GetPaymentBankViewDto>();
									
									for(int i=0;i<jsonArray.size();i++){
										
										JSONObject jsonObject=(JSONObject) jsonArray.get(i);
										
										getPaymentBankViewDto=new GetPaymentBankViewDto();
										
										getPaymentBankViewDto.setBankName(Utils.convertObjToString(jsonObject.get("BankName")));
										getPaymentBankViewDto.setBankOwner(Utils.convertObjToString(jsonObject.get("BankOwner")));
										getPaymentBankViewDto.setBankAccount( Utils.convertObjToString(jsonObject.get("BankAccount")));
										
										bankViewDtos.add(getPaymentBankViewDto);
									}
									
									GetPaymentBankViewDto bankViewDto=bankViewDtos.get(0);
									
									if(!Utils.isDataCheck(bankViewDto.getBankName(), null)
									||!Utils.isDataCheck(bankViewDto.getBankAccount(), null)
									||!Utils.isDataCheck(bankViewDto.getBankOwner(), null)){
										
										Utils.log("==========은행정보 존재 하는 다이얼로그 출력==========");
										
										autoScaleDialog=Utils.autoScaleDialog(AdministrationPayTution.this, R.layout.administration_pay_account_popup);
									
										autoSetTextViewNEvent(autoScaleDialog
											,resourceId
											,bankViewDto.getBankName()
											,bankViewDto.getBankAccount()
											,bankViewDto.getBankOwner());
										
									}else{
											
										Utils.log("==========은행정보 존재 하지 않는 다이얼로그 출력==========");
										autoScaleDialog=Utils.autoScaleDialog(AdministrationPayTution.this, R.layout.administration_pay_no_account_popup);
										TextView textView=(TextView)autoScaleDialog.findViewById(R.id.adminstration_no_account_closeBTN);
										textView.setOnClickListener(new View.OnClickListener() {
											
											@Override
											public void onClick(View v) {
												autoScaleDialog.dismiss();
												
											}
										});
									}
								
								}
							});
					}
			});
			
			return convertView;
		}
	};
	
	/**
	 *  리스트의 이벤트와 리스트 내부의 버튼 이벤트를 분리 동작 상황에 따라서 변경 될수 있기 때문에
	 *  controller 는 따로 빼 놓았다.
	 *  각 리스트별 클릭 콘트롤러
	 */
	
	AdapterView.OnItemClickListener onItemClickListener=new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
			Utils.log("=====================리스트 틀릭");
			
		}
	};
	/**
	 * autoScaleDialog TextView 공통정의 사항 이벤트와 등록 텍스트 한번에 등록
	 * Dialog 의 모든 처리를 이곳에서 한다. 
	 * @param autoScaleDialog
	 * @param resourceId
	 * @param bankName
	 * @param accountNum
	 * @param accountMaster
	 */
	public void autoSetTextViewNEvent(final AutoScaleDialog autoScaleDialog,int [] resourceId,final String bankName,final String accountNum,final String accountMaster){
		
		for(int resourceText=0;resourceText<resourceId.length;resourceText++){
			
			int resource=resourceId[resourceText];
			
			TextView commonDefine=(TextView)autoScaleDialog.findViewById(resource);
			
			switch (resourceText) {
			
			case 0:
				commonDefine.setText("은행명 :"+bankName);
				break;
			case 1:
				commonDefine.setText("계좌번호 :"+accountNum);
				break;
			case 2:
				commonDefine.setText("예금주 :"+accountMaster);
				break;
			case 3:
				commonDefine.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						autoScaleDialog.dismiss();
					}
				});
				break;
			case 4:
				/**
				 * SMS
				 */
				commonDefine.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Utils.log("======================SMS===============");
						preventTouch(true,autoScaleDialog);
						Utils.sendSMSData(AdministrationPayTution.this,"[스마트 글로리아]\n\n등록금 납부계좌 정보입니다." +
								"\n\n은행명:"+bankName+"\n계좌번호:"+accountNum+"\n예금주:"+accountMaster+"\n\n"+"cyber.gloriahrd.com");
						preventTouch(false,autoScaleDialog);
					}
						
				});
				break;
			case 5:
				/**
				 * KAKAO
				 */
				commonDefine.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						Utils.log("======================KAKAO===============");
						doubleClickPreventCount++;
						preventTouch(true,autoScaleDialog);
						Utils.kakaoProgress(AdministrationPayTution.this, "\n\n등록금 납부계좌 정보입니다." +
								"\n\n은행명:"+bankName+"\n계좌번호:"+accountNum+"\n예금주:"+accountMaster+"\n\n"+"cyber.gloriahrd.com"
								, "[스마트 글로리아]", true);
						preventTouch(false,autoScaleDialog);
					    }
				});
				break;
			case 6:
				/**
				 * Email
				 */
				commonDefine.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						Utils.log("======================EMAIL===============");
						preventTouch(true,autoScaleDialog);
						Utils.sendEmailData(AdministrationPayTution.this, ""
						, "등록금 납부계좌", "\n\n등록금 납부계좌 정보입니다." +
						"\n\n은행명:"+bankName+"\n계좌번호:"+accountNum+"\n예금주:"+accountMaster+"\n\n"+"cyber.gloriahrd.com");
						preventTouch(false,autoScaleDialog);
					}
				});
				break;
			default:
				break;
			}
		}
	}
	/**
	 * 차후 이슈 발생 여지 예방
	 * @param type
	 */
	public void preventTouch(boolean type,AutoScaleDialog autoScaleDialog){
		if(!autoScaleDialog.equals(null)){
		View view=(View)autoScaleDialog.findViewById(R.id.administration_pay_top_parent_Lay);
		Utils.preventTouchEventType(view, type);
		}
	}
	
}
